package com.apex.aolonfitdemo.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.apex.aolonfitdemo.R;
import com.apex.aolonfitdemo.databinding.ActivityOnlineDialBinding;
import com.apex.aolonfitdemo.dialog.WaitingDialog;
import com.apex.ax_bluetooth.callback.OtaCallback;
import com.apex.ax_bluetooth.core.EABleManager;
import com.apex.ax_bluetooth.model.EABleOta;
import com.apex.ax_bluetooth.utils.LogUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class OnlineDialActivity extends AppCompatActivity {
    ActivityOnlineDialBinding activityOnlineDialBinding;
    WaitingDialog waitingDialog;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x40) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                Toast.makeText(OnlineDialActivity.this, getString(R.string.ota_success), Toast.LENGTH_SHORT).show();
            } else if (msg.what == 0x41) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                Toast.makeText(OnlineDialActivity.this, getString(R.string.ota_failed), Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityOnlineDialBinding = ActivityOnlineDialBinding.inflate(getLayoutInflater());
        setContentView(activityOnlineDialBinding.getRoot());
        activityOnlineDialBinding.tool.setNavigationIcon(R.mipmap.exit_page);
        setSupportActionBar(activityOnlineDialBinding.tool);
        getSupportActionBar().setTitle(null);
        activityOnlineDialBinding.tool.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        activityOnlineDialBinding.install.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (waitingDialog == null) {
                    waitingDialog = new WaitingDialog(OnlineDialActivity.this);
                }
                if (!waitingDialog.isShowing()) {
                    waitingDialog.show();
                }
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        //将数据保存到文件
                        try {
                            InputStream inputStream = getResources().openRawResource(R.raw.gtr3_u099);
                            String filePath = save2File(inputStream, System.currentTimeMillis() + ".bin");
                            List<EABleOta> otaList = new ArrayList<>();
                            EABleOta eaBleOta = new EABleOta();
                            eaBleOta.setOtaType(EABleOta.OtaType.user_wf);
                            eaBleOta.setFilePath(filePath);
                            otaList.add(eaBleOta);
                            EABleManager.getInstance().otaUpdate(otaList, new OtaCallback() {
                                @Override
                                public void success() {
                                    if (mHandler != null) {
                                        mHandler.sendEmptyMessage(0x40);
                                    }
                                }

                                @Override
                                public void progress(int i) {
                                    LogUtils.e("Ota", "当前进度:" + i + "%");
                                }

                                @Override
                                public void hisUpdateId(int[] ints) {

                                }

                                @Override
                                public void mutualFail(int i) {
                                    if (mHandler != null) {
                                        mHandler.sendEmptyMessage(0x41);
                                    }
                                }

                            });
                        }catch (Exception e){
                            if (mHandler != null) {
                                mHandler.sendEmptyMessage(0x41);
                            }
                        }
                    }
                }.start();

            }
        });
    }
    private String save2File(InputStream inputStream, String fName) {

        try {
            File file = new File(getExternalCacheDir(), fName);
            if (!file.exists()) {
                file.createNewFile();
            }
            OutputStream os = new FileOutputStream(file);
            int read = 0;
            byte[] bytes = new byte[1024 * 1024];
            //先读后写
            while ((read = inputStream.read(bytes)) > 0) {
                byte[] wBytes = new byte[read];
                System.arraycopy(bytes, 0, wBytes, 0, read);
                os.write(wBytes);
            }
            os.flush();
            os.close();
            inputStream.close();
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        if (waitingDialog != null) {
            waitingDialog.dismiss();
            waitingDialog = null;
        }
        super.onDestroy();
    }
}
